package com.ssy.lingxi.report.handler.converter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.report.model.bo.tally.AfterSaleReplaceApplyTallyBO;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.ArrayList;
import java.util.List;

/**
 * 将自定义的Entity，与授信支付记录表中的Jsonb字段进行转换
 * @author 伍将
 * @date 2020/8/24
 * @version 2.0.0
 */
@Converter(autoApply = true)
public class JpaJsonToAfterSaleReplaceApplyTallyBOConverter implements AttributeConverter<List<AfterSaleReplaceApplyTallyBO>, String> {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(List<AfterSaleReplaceApplyTallyBO> attribute) {
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR, "权限实体转换Json错误");
        }
    }

    @Override
    public List<AfterSaleReplaceApplyTallyBO> convertToEntityAttribute(String dbData) {
        try {
            if (dbData == null) {
                return new ArrayList<>();
            }

            return objectMapper.readValue(dbData, new TypeReference<List<AfterSaleReplaceApplyTallyBO>>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR, "数据库json字段转换支付凭证实体错误");
        }
    }
}
